###
 # @Author: Logan.Li
 # @Gitee: https://gitee.com/attacker
 # @email: admin@attacker.club
 # @Date: 2025-02-10 22:12:07
 # @LastEditTime: 2025-02-10 22:12:16
 # @Description: 
### 
# 创建目录（如果不存在）
sudo mkdir -p /opt/task

# 写入脚本内容
sudo tee /opt/task/check_es.sh > /dev/null <<'EOF'
#!/bin/bash

ES_CONTAINER="elasticsearch"
SW_OAP_CONTAINER="skywalking-oap"

es_status=$(docker inspect -f '{{.State.Status}}' $ES_CONTAINER 2>/dev/null)

if [[ "$es_status" != "running" ]]; then
    echo "$(date '+%F %T') - $ES_CONTAINER is down (status: ${es_status:-not-exist}), attempting to restart..."
    
    if docker start $ES_CONTAINER > /dev/null 2>&1; then
        echo "$(date '+%F %T') - $ES_CONTAINER restarted successfully"
        
        sleep 5
        if docker restart $SW_OAP_CONTAINER > /dev/null 2>&1; then
            echo "$(date '+%F %T') - $SW_OAP_CONTAINER restarted successfully"
        else
            echo "$(date '+%F %T') - Failed to restart $SW_OAP_CONTAINER" >&2
        fi
    else
        echo "$(date '+%F %T') - Failed to restart $ES_CONTAINER" >&2
    fi
else
    echo "$(date '+%F %T') - $ES_CONTAINER is running normally"
fi
EOF

# 设置执行权限
sudo chmod +x /opt/task/check_es.sh

(crontab -l 2>/dev/null; echo "* * * * * /opt/task/check_es.sh >> /var/log/es_monitor.log 2>&1") | crontab -